package com.taotao.rop.service;

import com.rop.annotation.HttpAction;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.taotao.rop.database.domain.WechatRequest;
import com.taotao.rop.database.mapper.WechatRequestMapper;
import com.taotao.rop.response.BaseResponse;
import com.taotao.wechat.util.MessageUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@ServiceMethodBean(httpAction = HttpAction.POST, version = "1.0")
public class WechatRequestService {
    private static Logger logger = Logger.getLogger(WechatRequestService.class);
    @Autowired
    private WechatRequestMapper requestMapper;

    @ServiceMethod(method = "wechatRequest.insert")
    public Object insertWechatRequest(WechatRequest request) {
        Integer id = requestMapper.insertOne(request);

        BaseResponse<WechatRequest> response = new BaseResponse<WechatRequest>();
        if (id > 0) {
            response.setSuccess(true);
        }
        return response;
    }

    @ServiceMethod(method = "wechatRequest.update")
    public Object updateWechatRequest(WechatRequest request) {
        Integer id = requestMapper.updateOne(request);

        BaseResponse<WechatRequest> response = new BaseResponse<WechatRequest>();
        if (id > 0) {
            response.setSuccess(true);
        }
        return response;
    }

    @ServiceMethod(method = "wechatRequest.list")
    public Object getWechatRequestByPage(WechatRequest request) {
        List<WechatRequest> respList = requestMapper.getListByPage(request);

        //让respMsg只显示content
        for (WechatRequest req : respList) {
            if (StringUtils.isNotBlank(req.getRespmsg())) {
                try {
                    Map<String, String> requestMap = MessageUtil.parseXml(req.getRespmsg());
                    req.setRespmsg(requestMap.get("Content"));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            }
        }

        BaseResponse<List<WechatRequest>> response = new BaseResponse<List<WechatRequest>>();
        response.setSuccess(true);
        response.setMsg("" + requestMapper.getCount(request));
        response.setData(respList);
        return response;
    }
}
